const { User } = require("../models.js");
const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const koa2Req = require('koa2-request');
const secret = 'jwt demo';
const { username, password } = require("../database/config.js");
const fs = require('fs')
// let router = new Router()

let router = new Router({
    prefix:'/user'
})

router.get('/',async(ctx)=>{
    ctx.body  = "这是用户操作首页"
})





//用户登录
router.post('/login',async(ctx)=>{
	let { wxcode,wxAppID,wxAppSecret } = ctx.request.body;
    // 组合url
    let url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+wxAppID+'&secret='+wxAppSecret+'&js_code='+wxcode+'&grant_type=authorization_code';
    // 向微信服务器发送请求
    let res = await koa2Req(url);
    let { openid } = JSON.parse(res.body);

    if( openid ){
        const isopenid = await User.findAll({
            where:{ openid }
        });
		
        if(isopenid.length === 0){
            await User.create({ 
                openid
            })
        }
	
        //token签名 有效期为1小时
        const token = jwt.sign({
            openid:openid
        },'zouling',{expiresIn:'1h'})

        ctx.body = {
            message: '获取token成功',
            code:200,
            token
        }
    }else {
        ctx.body = {
            message: 'openid获取失败',
            code: -1
        }
    }
})



module.exports = router;